<?php
class Custom_Controller_Plugin_Image extends Zend_Controller_Plugin_Abstract
{
	
	protected $image;
	
	protected $thumbnailname;
	
	protected $waterthumbnailname;
	
	protected $imagefunc='imagejpeg';
	
	protected $imagecreatefromfunc='imagecreatefromjpeg';
	
	protected $waterimage='';
	
	protected $watermark_image;
	
	protected $suffix=array('gif','jpeg','png');
	
	protected $options=array('position'=>9,
							 'quality'=>100,
							 'pct'=>80);

	protected $thumbarray=array('width'=>400,
								'height'=>400);
	
	
    public function __construct($image,$waterimage=null,$options=null){
    	
    	if($this->isGD()){
	    	$this->image=$image;
	    	$this->waterimage=($waterimage === null)?$this->waterimage :$waterimage;
	    	$this->options = ($options === null) ? $this->options :$options;
    	}else{
    		return 'Please open GD!';
    	}
    }
     
    
    /**
     * 设置图片基本信息
     */
    public function	setImage(){
		
    	if(!$this->isExist($this->image)) return false;
		
    	$info=$this->getImageInfo($this->image);
		
    	switch($info['mime'])
		{
			case 'image/jpeg':
				$this->imagecreatefromfunc = function_exists('imagecreatefromjpeg') ? 'imagecreatefromjpeg' : '';
				$this->imagefunc = (imagetypes() & IMG_JPG) ? 'imagejpeg' : '';
				break;
			case 'image/gif':
				$this->imagecreatefromfunc = function_exists('imagecreatefromgif') ? 'imagecreatefromgif' : '';
				$this->imagefunc = (imagetypes() & IMG_GIF) ? 'imagegif' : '';
				break;
			case 'image/png':
				$this->imagecreatefromfunc = function_exists('imagecreatefrompng') ? 'imagecreatefrompng' : '';
				$this->imagefunc = (imagetypes() & IMG_PNG) ? 'imagepng' : '';
				break;
		}
		
		return true;
    }
    
    /**
     * 返回原图片地址
     */
    public function getImage(){
    	return $this->image;
    }
    
    /**
     * 取到原图片
     */
    public function getImagePath(){
    	$path=pathinfo($this->image);
    	return $path['dirname'].'/';
    }
    
    /**
     * 取得水印图片名
     */
    public function getWaterImage(){
    	return $this->waterimage;
    }
    
    /**
     * 设置水印图片路径
     * @param $image
     */
    public function setWaterImage($image=null){
    	
    	if($image===null) $image=PROJECT_ROOT.'/data/waterimage/waterimage.png';
    	
    	return $this->waterimage=$image;
    	
    }
    
    /**
     * 取得生成水印图片名称
     */
    public function getWaterThumbnailName(){
    	return $this->waterthumbnailname;
    }
    
   /**
    * 加水印图片
    * @param $name 重命名名称
    * @param $type 重命名方式
    * @param $dir 是否设置其他存放路径
    */
    public function setWaterThumbnailName($dir=null,$name=null,$type=null){
    	
    	$newname=($type)?$this->setNameType($type):$name;
		$dirname=$this->getImagePath();
		if($dir){
			if($name){
				$waterthumbnailname=$dir.$name;
			}else{
				$waterthumbnailname=$dir.$newname;
			}
		}else{
			$waterthumbnailname=$dirname.$newname;
		}
		
		$this->waterthumbnailname=$waterthumbnailname;
		
		return  $this->waterthumbnailname;
    }

    
	/**
	 * 加水印图片
	 * @param $name 重命名名称
	 * @param $type 重命名方式
	 * @param $dir 是否设置其他存放路径
	 */
	public function setThumbnailName($dir=null,$name=null,$type=null){
		
    	$newname=($type)?$this->setNameType($type):$name;
		$dirname=$this->getImagePath();
		if($dir){
			if($name){
				$thumbnailname=$dir.$name;
			}else{
				$thumbnailname=$dir.$newname;
			}
		}else{
			$thumbnailname=$dirname.$newname;
		}
		
		$this->thumbnailname=$thumbnailname;
		
		return  $this->thumbnailname;
    }
	
	/**
	 * 设置缩略图片大小
	 * @param $array
	 */
	public function setThumbarray($array=null){
		if($array){
			$this->thumbarray=$array;
		}
		return $this->thumbarray;	
	}
	
	/**
	 * 缩略图命名类型
	 * @param unknown_type $type
	 */
	public function setNameType($type){
		switch($type){

			case 'time':
    			$name=time();
    		break;

			case 'date':
    			$name=date('Y-m-d');
    		break;
    		
			case 'md5':
    			$name=md5(time());
    		break;

    		default:
				$info=$this->getImageInfo($this->image);
				list($img_w, $img_h) = $info;
				$name=$img_w.'_'.$img_h;
    		break;
		}

		return $name.'.'.strtolower(pathinfo($this->image, PATHINFO_EXTENSION));
	
	}

    
    /**
     * 返回缩后的图片地址
     */
    public function getThumbnail(){
    	
		$info=$this->getImageInfo($this->image);
		list($img_w, $img_h) = $info;
		
		$thumb_w=intval($this->thumbarray['0']);
		$thumb_h=intval($this->thumbarray['1']);
		
		$thumbnail_quality=min(100, intval($this->options['quality']));
		//缩略图片是否有高,宽数据
		if(($img_w <= $thumb_w) && ($img_h <= $thumb_h)) return false;
		//缩放比例
		$x_ratio = $thumb_w / $img_w;
		$y_ratio = $thumb_h / $img_h;
		
		if(($x_ratio * $img_h) < $thumb_h){
			$thumb['width'] = $thumb_w;
			$thumb['height'] = ceil($x_ratio * $img_h);
		}else{
			$thumb['width'] = ceil($y_ratio * $img_w);
			$thumb['height'] = $thumb_h;
		}
		
		if($this->setImage()){
			$imagecreatefromfunc = $this->imagecreatefromfunc;
			$thumb_img = $imagecreatefromfunc($this->image);
			$thumbnail_img = imagecreatetruecolor($thumb['width'], $thumb['height']);
			imagecopyresampled($thumbnail_img, $thumb_img ,0, 0, 0, 0, $thumb['width'], $thumb['height'], $img_w,$img_h);
			clearstatcache();
			$imagefunc = $this->imagefunc;
			$result = $this->imginfo['mime'] == 'image/jpeg' ? $imagefunc($thumbnail_img, $this->thumbnailname, $thumbnail_quality) : $imagefunc($thumbnail_img, $this->thumbnailname);
			
			$result=($result)?$this->thumbnailname:$result;
			
			return $result;
		}else{
			return false;
		}
    	
    	
    }
    
    /**
     * 设置水印参数
     */
    public function setWatermark(){
		
    	//水印图片是否存在
		if(!$this->isExist($this->waterimage)) return false;		
		if (!$this->isImage($this->waterimage)) return false;
		$waterimages['watermark_suffix']=$this->getSuffix($this->waterimage);
		//取到水印图片高,宽
		$watermarkinfo	= $this->getImageInfo($this->waterimage);
		$waterimages['watermark_width']	= $watermarkinfo[0];
		$waterimages['watermark_height']	= $watermarkinfo[1];
		
		//设置水印图片的位置,生成质量,高,宽等参数
		$waterimages['watermark_minwidth'] = intval($this->options['minwidth']);
		$waterimages['watermark_minheight'] = intval($this->options['minheight']);
		$waterimages['watermark_position'] = intval($this->options['position']);
		$waterimages['watermark_pct'] = min(100, intval($this->options['pct']));
		$waterimages['watermark_quality'] = min(100, intval($this->options['quality']));
		
		return $waterimages;
    
    }
    
    /**
     * 生成水印图片
     */
    public function getWatermark($target=null){
    	
		
			
		if($this->setImage()){
			
			$waterimages=$this->setWatermark();
			
			//根据不同的水印图片,调用不同的处理函数
			$this->watermark_image	= ($waterimages['watermark_suffix']== 'png')? @imagecreatefrompng($this->waterimage) : @imagecreatefromgif($this->waterimage);
			if(!$this->watermark_image) return false;
			//$this->waterthumbnailname = 'thumbnailname_'.$this->image;
			
			$info=$this->getImageInfo($this->image);
			list($img_w, $img_h) = $info;
			if(($img_w<=$waterimages['watermark_width'])||($img_h<=$waterimages['watermark_height'])) return false;
			$wmwidth = $img_w - $waterimages['watermark_width'];
			$wmheight = $img_h - $waterimages['watermark_height'];
			if($wmwidth < 10 || $wmheight < 10) return false;
			
			switch($waterimages['watermark_position'])
			{
				case 1:
					$x = +5;
					$y = +5;
					break;
				case 2:
					$x = $wmwidth / 2;
					$y = +5;
					break;
				case 3:
					$x = $wmwidth - 5;
					$y = +5;
					break;
				case 4:
					$x = +5;
					$y = $wmheight / 2;
					break;
				case 5:
					$x = $wmwidth / 2;
					$y = $wmheight / 2;
					break;
				case 6:
					$x = $wmwidth;
					$y = $wmheight / 2;
					break;
				case 7:
					$x = +5;
					$y = $wmheight - 5;
					break;
				case 8:
					$x = $wmwidth / 2;
					$y = $wmheight - 5;
					break;
				default:
					$x = $wmwidth - 5;
					$y = $wmheight - 5;
			}
			
			$im = imagecreatetruecolor($img_w, $img_h);
			$imagecreatefromfunc = $this->imagecreatefromfunc;
			$source_im = @$imagecreatefromfunc($this->image);
			imagecopy($im, $source_im, 0, 0, 0, 0, $img_w, $img_h);
			
			if($waterimages['watermark_suffix'] == 'png')
			{
				imagecopy($im, $this->watermark_image, $x, $y, 0, 0, $waterimages['watermark_width'], $waterimages['watermark_height']);
			}else{
				imagealphablending($this->watermark_image, true);
				imagecopymerge($im, $this->watermark_image, $x, $y, 0, 0, $waterimages['watermark_width'], $waterimages['watermark_height'],$waterimages['watermark_pct']);
			}
			clearstatcache();
			
			$imagefunc = $this->imagefunc;
			
			if($target===null){
				$this->waterthumbnailname=$this->image;
			}
			
			$result = ($info['mime'] == 'image/jpeg') ? $imagefunc($im, $this->waterthumbnailname, $waterimages['watermark_quality']) : $imagefunc($im, $this->waterthumbnailname);
			
			@imagedestroy($im);
			$result=($result)?$this->waterthumbnailname:$result;
			
			return $result;
		}else{
			
			return false;
		}
    }
    
    
    /**
     * 取到要生成缩略图片名
     */
    public function getThumbnailName(){
    	return $this->thumbnailname;
    }
    
    
    public function getImageInfo($image){
    	return $info= @getimagesize($image);
    }
    
    /**
     * 检查是否为图片
     */
    public function isImage($image){
    	if(in_array($this->getSuffix($image), $this->suffix)){
    		return true;
    	}else{
    		return false;
    	}
    }
    
    /**
     * 取到图片后缀名
     */
    public function getSuffix($image){
    	
    	return strtolower(pathinfo($image, PATHINFO_EXTENSION));
    }
    
 	/**
     * 检查文件是否存在
     * @param $image
     */
    public function isExist($image){
    	if (file_exists($image)){
    		return true;
    	}else{
    		return false;
    	}
    }
	
    /**
     * 检测是否打开GD库
     */
    public function isGD(){
    	if(!function_exists('imagecreatetruecolor') || !function_exists('imagecopyresampled') || !function_exists('imagejpeg')){
    		 return false;
    	}else{
    		 return true;
    	}
    }
}